package com.cqs.leetcode.sort;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lixiaowen
 * @create 2019-12-12
 */
public class MergeIntervals56 {


    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length <= 1) return intervals;
        //1. 数组首数子排序 -- 关键
        quickSort(intervals, 0, intervals.length - 1);
        List<int[]> list = new ArrayList<>();
        int[] cur = intervals[0];
        for (int i = 1; i < intervals.length; i++) {
            int[] arr = intervals[i];
            if (cur[1] < arr[0]) {
                //如[1,3][5,9]那么cur区间可以确定未比较左侧区间(没有交集)
                //将cur添加到结果集
                list.add(cur);
                cur = arr;
            } else {
                //两个区间合并成一个
                //注意： cur[0]一定比arr[0]小，但是cur[1]可能大于arr[1]
                cur[1] = Math.max(cur[1], arr[1]);
            }
        }
        list.add(cur);
        int[][] result = new int[list.size()][];
        list.toArray(result);
        return result;
    }

    /**
     * 首个数字(左区间)排序（升序）
     *
     * @param intervals
     * @param left
     * @param right
     */
    private void quickSort(int[][] intervals, final int left, final int right) {
        if (left >= right) return;
        int pivot = left;
        int l = left + 1, r = right;
        while (l <= r) {
            //不能包含空数组
            while (l <= r && intervals[l][0] <= intervals[pivot][0]) {
                ++l;
            }
            while (l <= r && intervals[pivot][0] < intervals[r][0]) {
                --r;
            }
            if (l < r) {
                swap(intervals, l, r);
            }
        }
        swap(intervals, pivot, r);
        quickSort(intervals, left, r - 1);
        quickSort(intervals, r + 1, right);
    }

    private void swap(int[][] arr, int i, int j) {
        int[] tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

}
